/**
 * 《缙青年》电子期刊 - 阅读器脚本
 * 开发者：缙云公司—韩剑
 */

// PDF阅读器管理器
const PDFReaderManager = {
    // 初始化
    init() {
        console.log('🚀 PDFReaderManager 开始初始化...');

        // 兼容性检查
        this.checkCompatibility();

        try {
            // DOM元素
            console.log('📋 获取DOM元素...');
            this.pdfViewer = Utils.dom.$('#pdfViewer');
            this.bookTitle = Utils.dom.$('#bookTitle');
            this.pdfLoading = Utils.dom.$('#pdfLoading');
            this.pdfCanvasContainer = Utils.dom.$('#pdfCanvasContainer');
            this.pdfCanvas = Utils.dom.$('#pdfCanvas');
            this.touchAreas = Utils.dom.$('#touchAreas');
            this.simplePageInfo = Utils.dom.$('#simplePageInfo');
            this.currentPageDisplay = Utils.dom.$('#currentPageDisplay');
            this.totalPagesDisplay = Utils.dom.$('#totalPagesDisplay');
            this.loadingProgress = Utils.dom.$('#loadingProgress');
            this.progressText = Utils.dom.$('#progressText');

            console.log('✅ DOM元素获取完成');

            // 验证关键DOM元素
            if (!this.pdfViewer) {
                throw new Error('找不到PDF查看器容器元素 (#pdfViewer)');
            }
            console.log('✅ 关键DOM元素验证通过');

        // 状态变量
        this.pdfDocument = null;
        this.currentPage = 1;
        this.totalPages = 0;
        this.scale = 1;
        this.isLoading = false;
        this.controlsTimeout = null;
        this.currentRenderTask = null;
        // 增强的页面缓存系统
        this.pageCache = new Map();
        this.maxCacheSize = this.getOptimalCacheSize();
        this.cacheStrategy = 'adaptive'; // adaptive, aggressive, conservative
        this.preloadQueue = new Set(); // 预加载队列
        this.isPreloading = false;
        this.soundEnabled = Utils.storage.get('soundEnabled', false); // 音效开关

        // 响应式相关属性
        this.currentBreakpoint = this.getCurrentBreakpoint();
        this.isLandscape = window.innerHeight < window.innerWidth;
        // 增强的性能统计
        this.performanceStats = {
            renderTimes: [],
            averageRenderTime: 0,
            slowRenderCount: 0,
            cacheHitTimes: [],
            averageCacheHitTime: 0,
            cacheHitCount: 0,
            cacheMissCount: 0,
            preloadSuccessCount: 0,
            preloadFailureCount: 0,
            memoryUsage: 0
        };

        // 资源优化配置
        this.resourceOptimization = {
            enableImageBitmap: 'createImageBitmap' in window,
            enableOffscreenCanvas: 'OffscreenCanvas' in window,
            enableWebGL: this.checkWebGLSupport(),
            maxConcurrentPreloads: this.isLowEndDevice() ? 1 : 2
        };

        this.navigationHistory = []; // 导航历史
        this.hasUnsavedProgress = false; // 是否有未保存的进度

        // 获取URL参数
        console.log('🔍 解析URL参数...');
        this.bookId = Utils.navigation.getUrlParam('book');
        this.initialPage = parseInt(Utils.navigation.getUrlParam('page')) || 1;

        console.log(`📖 书籍ID: ${this.bookId}, 初始页面: ${this.initialPage}`);

        if (!this.bookId) {
            console.error('❌ 缺少书籍参数');
            this.showError('参数错误', '缺少书籍参数，请从主页选择书籍', [
                '返回主页选择期刊',
                '检查URL参数是否正确',
                '刷新页面重试'
            ]);
            return;
        }

        console.log('🔍 检查PDF.js是否可用...');
        // 检查PDF.js是否可用
        if (typeof pdfjsLib === 'undefined') {
            console.error('❌ PDF.js库未加载');
            this.showError('加载错误', 'PDF渲染库未正确加载', [
                '刷新页面重试',
                '检查网络连接',
                '使用支持的浏览器'
            ]);
            return;
        }
        console.log('✅ PDF.js库已加载');

        console.log('🔗 绑定基础事件...');
        // 绑定事件
        try {
            this.bindEvents();
            console.log('✅ 基础事件绑定完成');
        } catch (error) {
            console.warn('⚠️ 基础事件绑定失败:', error.message);
        }

        console.log('⌨️ 键盘事件已在bindEvents中处理');

        console.log('👆 绑定触控事件...');
        // 绑定触控事件
        try {
            this.bindTouchEvents();
            console.log('✅ 触控事件绑定完成');
        } catch (error) {
            console.warn('⚠️ 触控事件绑定失败:', error.message);
        }

        console.log('🖥️ 绑定全屏事件...');
        // 绑定全屏事件
        try {
            this.bindFullscreenEvents();
            console.log('✅ 全屏事件绑定完成');
        } catch (error) {
            console.warn('⚠️ 全屏事件绑定失败:', error.message);
        }

        console.log('🍞 创建面包屑导航...');
        // 创建面包屑导航
        try {
            this.createBreadcrumb();
            console.log('✅ 面包屑导航创建完成');
        } catch (error) {
            console.warn('⚠️ 面包屑导航创建失败:', error.message);
        }

        console.log('📄 开始加载期刊...');
        // 加载PDF
        this.loadPDF();

        console.log('✅ PDFReaderManager 初始化完成');

        } catch (error) {
            console.error('❌ PDFReaderManager 初始化失败:', error);
            this.showError('初始化失败', '阅读器初始化过程中发生错误', [
                '刷新页面重试',
                '返回主页',
                '检查浏览器兼容性'
            ]);
        }
    },

    // 绑定事件
    bindEvents() {
        // 返回按钮
        const backBtn = Utils.dom.$('#backBtn');
        const homeBtn = Utils.dom.$('#homeBtn');

        if (backBtn) {
            Utils.dom.on(backBtn, 'click', () => {
                this.handleBackToHome();
            });
        }

        if (homeBtn) {
            Utils.dom.on(homeBtn, 'click', () => {
                this.handleBackToHome();
            });
        }

        // 移除控制面板相关的事件绑定

        // 触控区域
        this.bindTouchEvents();

        // 键盘事件
        Utils.dom.on(document, 'keydown', (e) => {
            // 如果在输入框中，不处理快捷键
            if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') {
                return;
            }

            switch (e.key) {
                case 'ArrowLeft':
                case 'ArrowUp':
                case 'PageUp':
                    e.preventDefault();
                    this.prevPage();
                    break;
                case 'ArrowRight':
                case 'ArrowDown':
                case 'PageDown':
                case ' ':
                    e.preventDefault();
                    this.nextPage();
                    break;
                case 'Home':
                    e.preventDefault();
                    this.goToPage(1);
                    break;
                case 'End':
                    e.preventDefault();
                    this.goToPage(this.totalPages);
                    break;
                case 'Escape':
                    e.preventDefault();
                    if (document.fullscreenElement) {
                        this.toggleFullscreen();
                    }
                    break;
                case 'f':
                case 'F':
                    if (!e.ctrlKey && !e.metaKey) {
                        e.preventDefault();
                        this.toggleFullscreen();
                    }
                    break;
                case '+':
                case '=':
                    if (e.ctrlKey || e.metaKey) {
                        e.preventDefault();
                        this.zoomIn();
                    }
                    break;
                case '-':
                    if (e.ctrlKey || e.metaKey) {
                        e.preventDefault();
                        this.zoomOut();
                    }
                    break;
                case '0':
                    if (e.ctrlKey || e.metaKey) {
                        e.preventDefault();
                        this.resetZoom();
                    }
                    break;
                case 'h':
                case 'H':
                    if (!e.ctrlKey && !e.metaKey) {
                        e.preventDefault();
                        this.handleBackToHome();
                    }
                    break;
                // 移除键盘帮助弹窗，专注移动端体验
            }
        });

        // 窗口大小变化
        Utils.dom.on(window, 'resize', Utils.debounce(() => {
            this.handleResize();
        }, 250));

        // 错误处理
        const errorRetryBtn = Utils.dom.$('#errorRetryBtn');
        const errorBackBtn = Utils.dom.$('#errorBackBtn');

        if (errorRetryBtn) {
            Utils.dom.on(errorRetryBtn, 'click', () => {
                Utils.error.hide();
                this.loadPDF();
            });
        }

        if (errorBackBtn) {
            Utils.dom.on(errorBackBtn, 'click', () => {
                Utils.navigation.goToHome();
            });
        }
    },

    // 绑定触控事件（简化版）
    bindTouchEvents() {
        const touchLeft = Utils.dom.$('#touchLeft');
        const touchRight = Utils.dom.$('#touchRight');

        // 手势识别状态（优化移动端）
        this.gestureState = {
            startX: 0,
            startY: 0,
            startTime: 0,
            isGesturing: false,
            threshold: 30, // 降低滑动阈值，更敏感
            timeThreshold: 800 // 增加时间阈值，更宽容
        };

        // 左侧区域 - 上一页
        if (touchLeft) {
            this.bindAreaEvents(touchLeft, 'prev');
        }

        // 右侧区域 - 下一页
        if (touchRight) {
            this.bindAreaEvents(touchRight, 'next');
        }

        // 移除控制面板相关事件

        // 全局手势事件
        this.bindGlobalGestures();
    },

    // 绑定区域事件
    bindAreaEvents(element, action) {
        // 触摸开始
        Utils.dom.on(element, 'touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            this.gestureState.startX = touch.clientX;
            this.gestureState.startY = touch.clientY;
            this.gestureState.startTime = Date.now();
            this.gestureState.isGesturing = true;
        }, { passive: false });

        // 触摸移动
        Utils.dom.on(element, 'touchmove', (e) => {
            if (!this.gestureState.isGesturing) return;

            const touch = e.touches[0];
            const deltaX = touch.clientX - this.gestureState.startX;
            const deltaY = touch.clientY - this.gestureState.startY;

            // 如果是垂直滑动，允许页面滚动
            if (Math.abs(deltaY) > Math.abs(deltaX)) {
                return;
            }

            // 水平滑动时阻止默认行为
            e.preventDefault();
        }, { passive: false });

        // 触摸结束
        Utils.dom.on(element, 'touchend', (e) => {
            if (!this.gestureState.isGesturing) return;

            const touch = e.changedTouches[0];
            const deltaX = touch.clientX - this.gestureState.startX;
            const deltaY = touch.clientY - this.gestureState.startY;
            const deltaTime = Date.now() - this.gestureState.startTime;

            this.gestureState.isGesturing = false;

            // 判断是否为有效手势
            const isSwipe = Math.abs(deltaX) > this.gestureState.threshold &&
                           deltaTime < this.gestureState.timeThreshold;

            if (isSwipe) {
                // 滑动手势
                this.createTouchFeedback(e);
                if (deltaX > 0) {
                    // 向右滑动 - 上一页
                    this.prevPage();
                } else {
                    // 向左滑动 - 下一页
                    this.nextPage();
                }
            } else if (Math.abs(deltaX) < 10 && Math.abs(deltaY) < 10) {
                // 点击手势
                this.createTouchFeedback(e);
                this.handleAreaAction(action);
            }
        });

        // 鼠标事件（桌面端）
        Utils.dom.on(element, 'click', (e) => {
            if (!Utils.responsive.isTouchDevice()) {
                this.createTouchFeedback(e);
                this.handleAreaAction(action);
            }
        });
    },

    // 处理区域动作（简化版）
    handleAreaAction(action) {
        switch (action) {
            case 'prev':
                this.prevPage();
                break;
            case 'next':
                this.nextPage();
                break;
        }
    },

    // 绑定全局手势
    bindGlobalGestures() {
        // 检查pdfViewer元素是否存在
        if (!this.pdfViewer) {
            console.warn('⚠️ pdfViewer元素不存在，跳过全局手势绑定');
            return;
        }

        console.log('🌐 绑定全局手势到pdfViewer元素');

        // 双击缩放
        let lastTap = 0;
        Utils.dom.on(this.pdfViewer, 'touchend', (e) => {
            const currentTime = Date.now();
            const tapLength = currentTime - lastTap;

            if (tapLength < 500 && tapLength > 0) {
                // 双击事件
                e.preventDefault();
                this.handleDoubleTap(e);
            }
            lastTap = currentTime;
        });

        // 移除长按控制面板功能

        // 窗口大小变化监听
        Utils.dom.on(window, 'resize', Utils.debounce(() => {
            this.handleWindowResize();
        }, 250));

        // 设备方向变化监听
        Utils.dom.on(window, 'orientationchange', () => {
            setTimeout(() => {
                this.handleOrientationChange();
            }, 100);
        });

        // 定期内存监控
        this.memoryMonitorInterval = setInterval(() => {
            this.monitorMemoryUsage();
        }, 30000); // 每30秒检查一次
    },

    // 检查浏览器兼容性
    checkCompatibility() {
        try {
            if (typeof CompatibilityManager !== 'undefined') {
                const compatibilityManager = new CompatibilityManager();
                const report = compatibilityManager.getCompatibilityReport();

                // 如果有严重兼容性问题，显示警告
                if (report.issues.length > 0) {
                    console.warn('检测到兼容性问题:', report.issues);
                    this.showCompatibilityWarning(report);
                }

                // 记录兼容性信息
                console.log('浏览器兼容性检查完成:', {
                    browser: report.browser,
                    compatible: report.compatible,
                    issues: report.issues.length,
                    warnings: report.warnings.length
                });

                // 存储兼容性信息供后续使用
                this.compatibilityReport = report;
            }
        } catch (error) {
            console.warn('兼容性检查失败:', error);
        }
    },

    // 显示兼容性警告
    showCompatibilityWarning(report) {
        const warningHtml = `
            <div style="background: #fff3cd; border: 1px solid #ffeaa7; padding: 15px; margin: 10px; border-radius: 4px; position: relative; z-index: 1000;">
                <h4 style="color: #856404; margin-top: 0;">⚠️ 浏览器兼容性警告</h4>
                <p>检测到您的浏览器可能存在兼容性问题：</p>
                <ul style="margin: 10px 0; padding-left: 20px;">
                    ${report.issues.map(issue => `<li>${issue}</li>`).join('')}
                </ul>
                ${report.recommendations.length > 0 ? `
                <p>建议：</p>
                <ul style="margin: 10px 0; padding-left: 20px;">
                    ${report.recommendations.map(rec => `<li>${rec}</li>`).join('')}
                </ul>
                ` : ''}
                <button onclick="this.parentElement.style.display='none'"
                        style="background: #856404; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">
                    我知道了
                </button>
            </div>
        `;

        // 在页面顶部插入警告
        const container = document.body;
        const warningDiv = document.createElement('div');
        warningDiv.innerHTML = warningHtml;
        container.insertBefore(warningDiv, container.firstChild);

        // 5秒后自动隐藏
        setTimeout(() => {
            if (warningDiv.parentElement) {
                warningDiv.style.display = 'none';
            }
        }, 5000);
    },

    // 处理双击事件
    handleDoubleTap(e) {
        // 双击切换缩放
        if (this.scale === 1.0) {
            this.zoomIn();
        } else {
            this.resetZoom();
        }
    },

    // 创建触控反馈效果
    createTouchFeedback(event) {
        let x, y, targetElement;

        if (event.touches && event.touches.length > 0) {
            // 触摸事件
            const touch = event.touches[0] || event.changedTouches[0];
            const rect = event.currentTarget.getBoundingClientRect();
            x = touch.clientX - rect.left;
            y = touch.clientY - rect.top;
            targetElement = event.currentTarget;
        } else {
            // 鼠标事件
            const rect = event.currentTarget.getBoundingClientRect();
            x = event.clientX - rect.left;
            y = event.clientY - rect.top;
            targetElement = event.currentTarget;
        }

        const feedback = document.createElement('div');
        feedback.className = 'touch-feedback';
        feedback.style.left = (x - 10) + 'px';
        feedback.style.top = (y - 10) + 'px';
        feedback.style.width = '20px';
        feedback.style.height = '20px';

        targetElement.appendChild(feedback);

        // 添加动画类
        requestAnimationFrame(() => {
            feedback.classList.add('active');
        });

        // 动画结束后移除元素
        setTimeout(() => {
            if (feedback.parentNode) {
                feedback.parentNode.removeChild(feedback);
            }
        }, 600);
    },

    // 创建翻页指示器
    createPageIndicator(direction) {
        // 移除现有指示器
        const existingIndicator = Utils.dom.$('.page-indicator');
        if (existingIndicator) {
            existingIndicator.remove();
        }

        const indicator = document.createElement('div');
        indicator.className = `page-indicator ${direction}`;

        const arrow = document.createElement('div');
        arrow.className = 'indicator-arrow';
        arrow.textContent = direction === 'prev' ? '←' : '→';

        const text = document.createElement('div');
        text.className = 'indicator-text';
        text.textContent = direction === 'prev' ? '上一页' : '下一页';

        indicator.appendChild(arrow);
        indicator.appendChild(text);

        this.pdfViewer.appendChild(indicator);

        // 显示动画
        requestAnimationFrame(() => {
            indicator.classList.add('show');
        });

        // 自动隐藏
        setTimeout(() => {
            indicator.classList.remove('show');
            setTimeout(() => {
                if (indicator.parentNode) {
                    indicator.parentNode.removeChild(indicator);
                }
            }, 300);
        }, 1000);
    },

    // 创建边界提示
    createBoundaryFeedback(type) {
        const feedback = document.createElement('div');
        feedback.className = `boundary-feedback ${type}`;

        const icon = document.createElement('div');
        icon.className = 'boundary-icon';
        icon.textContent = type === 'first' ? '⏮' : '⏭';

        const text = document.createElement('div');
        text.className = 'boundary-text';
        text.textContent = type === 'first' ? '已是第一页' : '已是最后一页';

        feedback.appendChild(icon);
        feedback.appendChild(text);

        this.pdfViewer.appendChild(feedback);

        // 显示动画
        requestAnimationFrame(() => {
            feedback.classList.add('show');
        });

        // 触觉反馈
        if (navigator.vibrate) {
            navigator.vibrate([50, 50, 50]);
        }

        // 自动隐藏
        setTimeout(() => {
            feedback.classList.remove('show');
            setTimeout(() => {
                if (feedback.parentNode) {
                    feedback.parentNode.removeChild(feedback);
                }
            }, 300);
        }, 1500);
    },

    // 加载PDF
    async loadPDF() {
        console.log('📄 loadPDF() 开始执行...');
        try {
            console.log('🔄 设置加载状态...');
            this.isLoading = true;
            this.showLoading();

            // 构建PDF文件路径
            const pdfPath = `pdfs/${this.getBookFilename(this.bookId)}`;
            console.log(`📁 PDF文件路径: ${pdfPath}`);

            // 更新书籍标题
            console.log('📝 更新书籍标题...');
            this.updateBookTitle();

            // 检查PDF.js是否可用
            if (typeof pdfjsLib === 'undefined') {
                throw new Error('PDF.js库未加载');
            }

            console.log('开始加载PDF:', pdfPath);

            // 加载PDF文档
            const loadingTask = pdfjsLib.getDocument({
                url: pdfPath,
                cMapUrl: 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/cmaps/',
                cMapPacked: true,
                // 添加错误处理配置
                verbosity: pdfjsLib.VerbosityLevel.ERRORS,
                // 禁用字体回退以提高性能
                disableFontFace: false,
                // 启用流式加载
                disableStream: false,
                // 禁用范围请求以提高兼容性
                disableRange: false,
                // 添加超时设置
                httpHeaders: {},
                // 最大重试次数
                maxImageSize: -1,
                // 启用工作线程
                useWorkerFetch: false
            });

            // 添加超时机制
            const timeoutPromise = new Promise((_, reject) => {
                setTimeout(() => {
                    reject(new Error('PDF加载超时（30秒）'));
                }, 30000);
            });

            // 监听加载进度
            loadingTask.onProgress = (progress) => {
                if (progress.total > 0) {
                    const percent = Math.round((progress.loaded / progress.total) * 100);
                    this.updateLoadingProgress(percent);
                } else {
                    // 如果无法获取总大小，显示加载动画
                    this.updateLoadingProgress(50);
                }
            };

            this.pdfDocument = await Promise.race([loadingTask.promise, timeoutPromise]);

            // 验证PDF文档对象
            if (!this.pdfDocument) {
                throw new Error('PDF文档加载失败');
            }

            this.totalPages = this.pdfDocument.numPages || 0;

            // 验证PDF文档
            if (this.totalPages === 0) {
                throw new Error('PDF文档为空或页数无法获取');
            }

            console.log(`PDF文档验证成功: ${this.totalPages}页`);

            // 移除阅读进度加载

            // 更新页面信息
            this.updatePageInfo();

            // 跳转到指定页面
            this.currentPage = Math.min(this.initialPage, this.totalPages);

            // 渲染当前页面
            await this.renderPage(this.currentPage);

            // 显示PDF
            this.showPDF();

            console.log(`期刊加载成功: ${this.totalPages}页`);

            // 显示开始阅读提示
            this.showStartReadingHint();

        } catch (error) {
            console.error('加载期刊失败:', error);

            // 根据错误类型提供不同的错误信息
            let errorTitle = '加载失败';
            let errorMessage = '无法加载期刊文件';
            let solutions = [
                '检查网络连接是否正常',
                '确认期刊文件是否存在',
                '尝试刷新页面重新加载',
                '返回主页选择其他期刊'
            ];

            if (error.name === 'MissingPDFException') {
                errorTitle = '文件不存在';
                errorMessage = '找不到指定的PDF文件';
                solutions = [
                    '确认文件名是否正确',
                    '检查pdfs目录下是否有该文件',
                    '返回主页选择其他期刊'
                ];
            } else if (error.name === 'InvalidPDFException') {
                errorTitle = '文件格式错误';
                errorMessage = 'PDF文件已损坏或格式不正确';
                solutions = [
                    '尝试重新下载PDF文件',
                    '检查文件是否完整',
                    '联系管理员获取正确文件'
                ];
            } else if (error.message.includes('PDF.js')) {
                errorTitle = '浏览器兼容性问题';
                errorMessage = '当前浏览器不支持PDF显示功能';
                solutions = [
                    '升级到最新版本浏览器',
                    '使用Chrome或Firefox浏览器',
                    '启用JavaScript功能'
                ];
            }

            this.showError(errorTitle, errorMessage, solutions);
        } finally {
            this.isLoading = false;
        }
    },

    // 获取书籍文件名
    getBookFilename(bookId) {
        // 直接使用bookId作为文件名（不含扩展名）
        // 如果bookId已经包含.pdf扩展名，直接返回
        if (bookId.endsWith('.pdf')) {
            return bookId;
        }
        // 否则添加.pdf扩展名
        return `${bookId}.pdf`;
    },

    // 更新书籍标题
    updateBookTitle() {
        // 直接使用bookId作为标题
        const title = this.bookId || '电子期刊';

        if (this.bookTitle) {
            this.bookTitle.textContent = title;
        }
        document.title = `${title} - 《缙青年》电子期刊`;

        console.log(`📝 书籍标题已更新: ${title}`);
    },

    // 更新加载进度
    updateLoadingProgress(percent) {
        if (this.loadingProgress) {
            this.loadingProgress.style.width = percent + '%';
        }
        if (this.progressText) {
            this.progressText.textContent = percent + '%';
        }
    },

    // 渲染页面
    async renderPage(pageNum) {
        if (!this.pdfDocument || this.isLoading) return;

        const renderStartTime = performance.now();

        try {
            // 验证页码范围
            if (pageNum < 1 || pageNum > this.totalPages) {
                console.warn(`页码超出范围: ${pageNum}, 总页数: ${this.totalPages}`);
                return;
            }

            // 取消之前的渲染任务
            if (this.currentRenderTask) {
                this.currentRenderTask.cancel();
            }

            // 尝试从缓存渲染
            if (this.renderFromCache(pageNum)) {
                // 更新缓存命中统计
                this.performanceStats.cacheHitCount++;

                // 更新当前页面信息
                this.currentPage = pageNum;
                this.updatePageInfo();

                // 预加载相邻页面
                this.preloadAdjacentPages(pageNum);

                // 更新URL参数
                Utils.navigation.setUrlParam('page', pageNum);

                console.log(`从缓存快速渲染页面: ${pageNum}`);
                return;
            }

            // 缓存未命中
            this.performanceStats.cacheMissCount++;

            const page = await this.pdfDocument.getPage(pageNum);
            const viewport = this.calculateViewport(page);

            // 设置画布尺寸
            const canvas = this.pdfCanvas;
            const context = canvas.getContext('2d');

            // 清除之前的内容
            context.clearRect(0, 0, canvas.width, canvas.height);

            // 设置高DPI支持
            const devicePixelRatio = window.devicePixelRatio || 1;
            canvas.width = viewport.width * devicePixelRatio;
            canvas.height = viewport.height * devicePixelRatio;
            canvas.style.width = viewport.width + 'px';
            canvas.style.height = viewport.height + 'px';

            // 缩放上下文以支持高DPI
            context.scale(devicePixelRatio, devicePixelRatio);

            // 渲染页面
            const renderContext = {
                canvasContext: context,
                viewport: viewport,
                // 启用文本选择
                textLayer: null,
                // 启用注释
                annotationLayer: null
            };

            // 开始渲染
            this.currentRenderTask = page.render(renderContext);
            await this.currentRenderTask.promise;

            // 渲染完成，清除任务引用
            this.currentRenderTask = null;

            // 更新当前页面
            this.currentPage = pageNum;
            this.updatePageInfo();

            // 添加到页面历史
            this.addPageToHistory(pageNum);

            // 预加载相邻页面
            this.preloadAdjacentPages(pageNum);

            // 记录性能统计
            const renderTime = performance.now() - renderStartTime;
            this.recordRenderPerformance(renderTime);

            console.log(`页面 ${pageNum} 渲染完成 (${renderTime.toFixed(2)}ms)`);

        } catch (error) {
            // 如果是取消操作，不显示错误
            if (error.name === 'RenderingCancelledException') {
                console.log('渲染被取消');
                return;
            }

            console.error('渲染页面失败:', error);

            let errorMessage = '无法显示PDF页面';
            if (error.message.includes('Invalid page')) {
                errorMessage = `页面 ${pageNum} 不存在或已损坏`;
            } else if (error.message.includes('Canvas')) {
                errorMessage = '画布渲染失败，请尝试刷新页面';
            }

            this.showError('渲染失败', errorMessage, [
                '尝试刷新当前页面',
                '重新加载PDF文档',
                '检查设备内存是否充足',
                '返回主页选择其他期刊'
            ]);
        }
    },

    // 计算视口（140%放大显示）
    calculateViewport(page) {
        const container = this.pdfCanvasContainer;
        const containerWidth = (container.clientWidth - 32); // 减去padding
        const containerHeight = (container.clientHeight - 32);

        const originalViewport = page.getViewport({ scale: 1 });
        const scaleX = containerWidth / originalViewport.width;
        const scaleY = containerHeight / originalViewport.height;

        // 基础缩放比例
        let baseScale = Math.max(scaleX, scaleY)*1;

        // 应用140%放大
        let scale = baseScale * 1;

        // 根据设备类型进行微调
        if (this.isMobileDevice()) {
            // 移动设备：稍微减少放大倍数以确保可读性
            scale = baseScale * 1;
        } else if (this.isTabletDevice()) {
            // 平板设备：保持140%
            scale = baseScale * 1;
        } else {
            // 桌面设备：140%放大
            scale = baseScale * 1;
        }

        // 横屏模式下的特殊处理
        if (this.isLandscape && this.isMobileDevice()) {
            scale = baseScale * 1; // 横屏时适度放大
        }

        // 限制最大缩放比例
        this.scale = Math.min(scale, 3); // 提高最大缩放限制

        console.log(`📏 PDF缩放设置: 基础=${baseScale.toFixed(2)}, 最终=${this.scale.toFixed(2)} (140%放大)`);

        return page.getViewport({ scale: this.scale });
    },

    // 上一页
    async prevPage() {
        if (this.isLoading) return;

        if (this.currentPage > 1) {
            this.playPageTurnSound();
            await this.renderPageWithTransition(this.currentPage - 1, 'prev');
        }
        // 移除边界提示，静默处理
    },

    // 下一页
    async nextPage() {
        if (this.isLoading) return;

        if (this.currentPage < this.totalPages) {
            this.playPageTurnSound();
            await this.renderPageWithTransition(this.currentPage + 1, 'next');
        }
        // 移除边界提示，静默处理
    },

    // 带过渡效果的页面渲染
    async renderPageWithTransition(pageNum, direction = 'next') {
        if (!this.pdfCanvasContainer) return;

        try {
            // 添加过渡效果类
            const container = this.pdfCanvasContainer;
            container.classList.add('page-transitioning');

            // 根据方向添加不同的过渡效果
            if (direction === 'next') {
                container.classList.add('slide-left');
            } else {
                container.classList.add('slide-right');
            }

            // 短暂延迟后开始渲染
            setTimeout(async () => {
                await this.renderPage(pageNum);

                // 移除过渡效果类
                setTimeout(() => {
                    container.classList.remove('page-transitioning', 'slide-left', 'slide-right');
                }, 150);
            }, 50);

        } catch (error) {
            console.error('页面过渡失败:', error);
            // 降级到普通渲染
            await this.renderPage(pageNum);
        }
    },

    // 显示页面加载指示器
    showPageLoadingIndicator() {
        let indicator = Utils.dom.$('.page-loading-indicator');
        if (!indicator) {
            indicator = document.createElement('div');
            indicator.className = 'page-loading-indicator';
            indicator.innerHTML = `
                <div class="loading-spinner-small"></div>
                <span class="loading-text-small">加载中...</span>
            `;
            this.pdfViewer.appendChild(indicator);
        }

        indicator.classList.add('show');
    },

    // 隐藏页面加载指示器
    hidePageLoadingIndicator() {
        const indicator = Utils.dom.$('.page-loading-indicator');
        if (indicator) {
            indicator.classList.remove('show');
        }
    },

    // 播放翻页音效
    playPageTurnSound() {
        if (!this.soundEnabled) return;

        try {
            // 使用Web Audio API创建简单的翻页音效
            const audioContext = new (window.AudioContext || window.webkitAudioContext)();
            const oscillator = audioContext.createOscillator();
            const gainNode = audioContext.createGain();

            oscillator.connect(gainNode);
            gainNode.connect(audioContext.destination);

            // 设置音效参数
            oscillator.frequency.setValueAtTime(800, audioContext.currentTime);
            oscillator.frequency.exponentialRampToValueAtTime(400, audioContext.currentTime + 0.1);

            gainNode.gain.setValueAtTime(0.1, audioContext.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, audioContext.currentTime + 0.1);

            oscillator.start(audioContext.currentTime);
            oscillator.stop(audioContext.currentTime + 0.1);
        } catch (error) {
            console.warn('音效播放失败:', error);
        }
    },

    // 切换音效开关
    toggleSound() {
        this.soundEnabled = !this.soundEnabled;
        Utils.storage.set('soundEnabled', this.soundEnabled);

        // 播放测试音效
        if (this.soundEnabled) {
            this.playPageTurnSound();
        }

        return this.soundEnabled;
    },

    // 处理音效切换
    handleSoundToggle() {
        const newState = this.toggleSound();
        this.updateSoundButton(newState);

        // 移除提示弹窗，只更新按钮状态
    },

    // 更新音效按钮
    updateSoundButton(enabled) {
        const soundBtn = Utils.dom.$('#soundToggleBtn');
        if (soundBtn) {
            const icon = soundBtn.querySelector('.icon');
            if (icon) {
                icon.textContent = enabled ? '🔊' : '🔇';
            }
            soundBtn.title = enabled ? '关闭音效' : '开启音效';
        }
    },

    // 显示音效切换提示
    showSoundToggleToast(enabled) {
        // 移除现有提示
        const existingToast = Utils.dom.$('.sound-toggle-toast');
        if (existingToast) {
            existingToast.remove();
        }

        const toast = document.createElement('div');
        toast.className = 'sound-toggle-toast';
        toast.innerHTML = `
            <div class="toast-icon">${enabled ? '🔊' : '🔇'}</div>
            <div class="toast-text">${enabled ? '音效已开启' : '音效已关闭'}</div>
        `;

        this.pdfViewer.appendChild(toast);

        // 显示动画
        requestAnimationFrame(() => {
            toast.classList.add('show');
        });

        // 自动隐藏
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => {
                if (toast.parentNode) {
                    toast.parentNode.removeChild(toast);
                }
            }, 300);
        }, 2000);
    },

    // 记录渲染性能
    recordRenderPerformance(renderTime) {
        this.performanceStats.renderTimes.push(renderTime);

        // 只保留最近50次的记录
        if (this.performanceStats.renderTimes.length > 50) {
            this.performanceStats.renderTimes.shift();
        }

        // 计算平均渲染时间
        const sum = this.performanceStats.renderTimes.reduce((a, b) => a + b, 0);
        this.performanceStats.averageRenderTime = sum / this.performanceStats.renderTimes.length;

        // 记录慢渲染次数（超过1秒）
        if (renderTime > 1000) {
            this.performanceStats.slowRenderCount++;
        }

        // 如果渲染时间过长，给出优化建议
        if (renderTime > 2000) {
            console.warn(`页面渲染较慢 (${renderTime.toFixed(2)}ms)，建议：`);
            console.warn('1. 检查设备性能');
            console.warn('2. 关闭其他应用程序');
            console.warn('3. 降低PDF质量设置');
        }
    },

    // 获取性能统计
    getPerformanceStats() {
        return {
            ...this.performanceStats,
            cacheHitRate: this.pageCache.size > 0 ?
                (this.pageCache.size / Math.max(this.currentPage, 1)) * 100 : 0
        };
    },

    // 优化建议
    getOptimizationSuggestions() {
        const stats = this.getPerformanceStats();
        const suggestions = [];

        if (stats.averageRenderTime > 800) {
            suggestions.push('渲染速度较慢，建议降低PDF质量或升级设备');
        }

        if (stats.cacheHitRate < 50) {
            suggestions.push('缓存命中率较低，建议增加缓存大小');
        }

        if (stats.slowRenderCount > 5) {
            suggestions.push('频繁出现慢渲染，建议检查设备性能');
        }

        return suggestions;
    },

    // 处理返回主页
    handleBackToHome() {
        // 直接返回主页，不显示确认弹窗
        this.goToHome();
    },

    // 显示退出确认对话框
    showExitConfirmation() {
        const modal = document.createElement('div');
        modal.className = 'exit-confirmation-modal';
        modal.innerHTML = `
            <div class="exit-confirmation-content">
                <div class="exit-icon">📖</div>
                <h3 class="exit-title">确认退出阅读？</h3>
                <p class="exit-message">您的阅读进度已自动保存</p>
                <div class="exit-progress-info">
                    <span>当前进度：第 ${this.currentPage} 页 / 共 ${this.totalPages} 页</span>
                    <div class="exit-progress-bar">
                        <div class="exit-progress-fill" style="width: ${(this.currentPage / this.totalPages * 100).toFixed(1)}%"></div>
                    </div>
                </div>
                <div class="exit-actions">
                    <button class="btn btn-secondary" id="exitCancelBtn">继续阅读</button>
                    <button class="btn btn-primary" id="exitConfirmBtn">返回主页</button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // 显示动画
        requestAnimationFrame(() => {
            modal.classList.add('show');
        });

        // 绑定事件
        const cancelBtn = modal.querySelector('#exitCancelBtn');
        const confirmBtn = modal.querySelector('#exitConfirmBtn');

        cancelBtn.onclick = () => {
            this.hideExitConfirmation(modal);
        };

        confirmBtn.onclick = () => {
            this.hideExitConfirmation(modal);
            this.goToHome();
        };

        // 点击外部关闭
        modal.onclick = (e) => {
            if (e.target === modal) {
                this.hideExitConfirmation(modal);
            }
        };

        // ESC键关闭
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                this.hideExitConfirmation(modal);
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
    },

    // 隐藏退出确认对话框
    hideExitConfirmation(modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            if (modal.parentNode) {
                modal.parentNode.removeChild(modal);
            }
        }, 300);
    },

    // 返回主页
    goToHome() {
        // 记录导航历史
        this.addToNavigationHistory('home', {
            from: 'reader',
            bookId: this.bookId,
            page: this.currentPage,
            timestamp: Date.now()
        });

        // 清理资源
        this.cleanup();

        // 跳转到主页
        Utils.navigation.goToHome();
    },

    // 添加到导航历史
    addToNavigationHistory(action, data) {
        this.navigationHistory.push({
            action,
            data,
            timestamp: Date.now()
        });

        // 只保留最近20条记录
        if (this.navigationHistory.length > 20) {
            this.navigationHistory.shift();
        }

        // 保存到本地存储
        Utils.storage.set('navigationHistory', this.navigationHistory);
    },

    // 获取导航历史
    getNavigationHistory() {
        return Utils.storage.get('navigationHistory', []);
    },

    // 面包屑导航
    updateBreadcrumb() {
        const breadcrumb = Utils.dom.$('.breadcrumb');
        if (!breadcrumb) {
            this.createBreadcrumb();
            return;
        }

        const bookTitle = this.getBookTitle();
        breadcrumb.innerHTML = `
            <span class="breadcrumb-item">
                <a href="index.html" class="breadcrumb-link">主页</a>
            </span>
            <span class="breadcrumb-separator">›</span>
            <span class="breadcrumb-item current">
                ${bookTitle}
            </span>
        `;
    },

    // 创建面包屑导航
    createBreadcrumb() {
        const header = Utils.dom.$('.reader-header');
        if (!header) return;

        const breadcrumb = document.createElement('div');
        breadcrumb.className = 'breadcrumb';

        // 插入到标题前面
        const bookInfo = header.querySelector('.book-info');
        if (bookInfo) {
            header.insertBefore(breadcrumb, bookInfo);
        }

        this.updateBreadcrumb();
    },

    // 获取书籍标题
    getBookTitle() {
        const titleMap = {
            'jinyouth-issue3': '《缙青年》第三期'
        };
        return titleMap[this.bookId] || '电子期刊';
    },

    // 页面跳转历史管理
    addPageToHistory(pageNum) {
        // 记录页面访问历史
        const pageHistory = Utils.storage.get(`pageHistory_${this.bookId}`, []);

        // 避免重复记录相同页面
        if (pageHistory.length === 0 || pageHistory[pageHistory.length - 1] !== pageNum) {
            pageHistory.push(pageNum);

            // 只保留最近50页的历史
            if (pageHistory.length > 50) {
                pageHistory.shift();
            }

            Utils.storage.set(`pageHistory_${this.bookId}`, pageHistory);
        }
    },

    // 获取页面历史
    getPageHistory() {
        return Utils.storage.get(`pageHistory_${this.bookId}`, []);
    },

    // 跳转到历史页面
    goToHistoryPage(index) {
        const history = this.getPageHistory();
        if (index >= 0 && index < history.length) {
            const pageNum = history[index];
            this.goToPage(pageNum);
        }
    },

    // 显示键盘快捷键帮助
    showKeyboardHelp() {
        const modal = document.createElement('div');
        modal.className = 'keyboard-help-modal';
        modal.innerHTML = `
            <div class="keyboard-help-content">
                <div class="help-header">
                    <h3 class="help-title">键盘快捷键</h3>
                    <button class="help-close" id="helpCloseBtn">×</button>
                </div>
                <div class="help-body">
                    <div class="help-section">
                        <h4>页面导航</h4>
                        <div class="help-item">
                            <span class="help-key">← ↑ PageUp</span>
                            <span class="help-desc">上一页</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">→ ↓ PageDown 空格</span>
                            <span class="help-desc">下一页</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">Home</span>
                            <span class="help-desc">第一页</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">End</span>
                            <span class="help-desc">最后一页</span>
                        </div>
                    </div>
                    <div class="help-section">
                        <h4>视图控制</h4>
                        <div class="help-item">
                            <span class="help-key">F</span>
                            <span class="help-desc">切换全屏</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">Ctrl/Cmd + +</span>
                            <span class="help-desc">放大</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">Ctrl/Cmd + -</span>
                            <span class="help-desc">缩小</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">Ctrl/Cmd + 0</span>
                            <span class="help-desc">重置缩放</span>
                        </div>
                    </div>
                    <div class="help-section">
                        <h4>其他功能</h4>
                        <div class="help-item">
                            <span class="help-key">H</span>
                            <span class="help-desc">返回主页</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">Esc</span>
                            <span class="help-desc">退出全屏/隐藏控制面板</span>
                        </div>
                        <div class="help-item">
                            <span class="help-key">?</span>
                            <span class="help-desc">显示此帮助</span>
                        </div>
                    </div>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        // 显示动画
        requestAnimationFrame(() => {
            modal.classList.add('show');
        });

        // 绑定关闭事件
        const closeBtn = modal.querySelector('#helpCloseBtn');
        closeBtn.onclick = () => {
            this.hideKeyboardHelp(modal);
        };

        // 点击外部关闭
        modal.onclick = (e) => {
            if (e.target === modal) {
                this.hideKeyboardHelp(modal);
            }
        };

        // ESC键关闭
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                this.hideKeyboardHelp(modal);
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
    },

    // 隐藏键盘帮助
    hideKeyboardHelp(modal) {
        modal.classList.remove('show');
        setTimeout(() => {
            if (modal.parentNode) {
                modal.parentNode.removeChild(modal);
            }
        }, 300);
    },

    // 跳转到指定页面
    async goToPage(pageNum) {
        const targetPage = Math.max(1, Math.min(pageNum, this.totalPages));
        if (targetPage !== this.currentPage) {
            await this.renderPage(targetPage);
        }
    },

    // 更新页面信息（简化版）
    updatePageInfo() {
        // 更新简化的页面信息显示
        if (this.currentPageDisplay) {
            this.currentPageDisplay.textContent = this.currentPage;
        }
        if (this.totalPagesDisplay) {
            this.totalPagesDisplay.textContent = this.totalPages;
        }

        // 更新响应式页面信息
        this.updateResponsivePageInfo();

        // 更新URL
        Utils.navigation.setUrlParam('page', this.currentPage);
    },

    // 移除所有进度记录相关的函数

    // 移除控制按钮状态更新函数

    // 移除所有进度记录和统计相关的函数

    // 获取最优缓存大小
    getOptimalCacheSize() {
        // 基于设备内存和性能动态调整缓存大小
        const deviceMemory = navigator.deviceMemory || 4; // GB
        const isLowEndDevice = this.isLowEndDevice();

        if (isLowEndDevice) {
            return 3; // 低端设备：3页
        } else if (deviceMemory >= 8) {
            return 10; // 高端设备：10页
        } else if (deviceMemory >= 4) {
            return 7; // 中端设备：7页
        } else {
            return 5; // 默认：5页
        }
    },

    // 检测是否为低端设备
    isLowEndDevice() {
        // 检查硬件并发数
        const hardwareConcurrency = navigator.hardwareConcurrency || 2;

        // 检查连接类型
        const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
        const isSlowConnection = connection && (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g');

        // 检查设备内存
        const deviceMemory = navigator.deviceMemory || 4;

        return hardwareConcurrency <= 2 || isSlowConnection || deviceMemory < 2;
    },

    // 获取当前断点
    getCurrentBreakpoint() {
        const width = window.innerWidth;
        if (width <= 320) return 'xs';
        if (width <= 480) return 'sm';
        if (width <= 768) return 'md';
        if (width <= 1024) return 'lg';
        return 'xl';
    },

    // 检查是否为移动设备
    isMobileDevice() {
        return this.currentBreakpoint === 'xs' || this.currentBreakpoint === 'sm';
    },

    // 检查是否为平板设备
    isTabletDevice() {
        return this.currentBreakpoint === 'md' || this.currentBreakpoint === 'lg';
    },

    // 响应式渲染优化
    getOptimalScale() {
        const containerWidth = this.pdfCanvasContainer.clientWidth;
        const containerHeight = this.pdfCanvasContainer.clientHeight;

        // 根据设备类型调整缩放策略
        if (this.isMobileDevice()) {
            // 移动设备：优先适应宽度
            return Math.min(containerWidth / 600, containerHeight / 800) * 0.95;
        } else if (this.isTabletDevice()) {
            // 平板设备：平衡宽度和高度
            return Math.min(containerWidth / 800, containerHeight / 1000) * 0.9;
        } else {
            // 桌面设备：保持原有逻辑
            return Math.min(containerWidth / 1000, containerHeight / 1200) * 0.85;
        }
    },

    // 响应式页面信息更新
    updateResponsivePageInfo() {
        if (!this.simplePageInfo) return;

        // 根据设备类型调整页面信息显示
        if (this.isMobileDevice() && this.isLandscape) {
            // 移动设备横屏：使用更紧凑的显示
            this.simplePageInfo.style.fontSize = '10px';
            this.simplePageInfo.style.padding = '2px 4px';
        } else {
            // 其他情况：使用CSS默认样式
            this.simplePageInfo.style.fontSize = '';
            this.simplePageInfo.style.padding = '';
        }
    },

    // 处理窗口大小变化
    handleWindowResize() {
        const newBreakpoint = this.getCurrentBreakpoint();
        const wasLandscape = this.isLandscape;
        this.isLandscape = window.innerHeight < window.innerWidth;

        // 如果断点或方向发生变化，重新渲染当前页面
        if (newBreakpoint !== this.currentBreakpoint || wasLandscape !== this.isLandscape) {
            this.currentBreakpoint = newBreakpoint;
            console.log(`响应式变化: ${newBreakpoint}, 横屏: ${this.isLandscape}`);

            // 重新渲染当前页面以适应新的尺寸
            if (this.currentPage && this.pdfDocument) {
                this.renderPage(this.currentPage);
            }

            // 更新页面信息显示
            this.updatePageInfo();
        }
    },

    // 处理设备方向变化
    handleOrientationChange() {
        console.log('设备方向变化');
        this.handleWindowResize();

        // 强制重新计算布局
        if (this.pdfCanvasContainer) {
            this.pdfCanvasContainer.style.height = 'auto';
            setTimeout(() => {
                this.pdfCanvasContainer.style.height = '';
            }, 50);
        }
    },

    // 移除所有控制面板相关的函数

    // 显示加载状态
    showLoading() {
        if (this.pdfLoading) Utils.dom.show(this.pdfLoading);
        if (this.pdfCanvasContainer) Utils.dom.hide(this.pdfCanvasContainer);
        if (this.touchAreas) Utils.dom.hide(this.touchAreas);
        if (this.simplePageInfo) Utils.dom.hide(this.simplePageInfo);
    },

    // 显示PDF
    showPDF() {
        if (this.pdfLoading) Utils.dom.hide(this.pdfLoading);
        if (this.pdfCanvasContainer) Utils.dom.show(this.pdfCanvasContainer);
        if (this.touchAreas) Utils.dom.show(this.touchAreas);
        if (this.simplePageInfo) Utils.dom.show(this.simplePageInfo);
    },

    // 显示错误
    showError(title, message) {
        if (this.pdfLoading) Utils.dom.hide(this.pdfLoading);
        if (this.pdfCanvasContainer) Utils.dom.hide(this.pdfCanvasContainer);
        if (this.touchAreas) Utils.dom.hide(this.touchAreas);
        if (this.simplePageInfo) Utils.dom.hide(this.simplePageInfo);

        Utils.error.show(
            title,
            message,
            [
                '检查网络连接是否正常',
                '确认PDF文件是否存在',
                '尝试刷新页面重新加载',
                '返回主页选择其他期刊'
            ],
            () => this.loadPDF(),
            () => Utils.navigation.goToHome()
        );
    },

    // 处理窗口大小变化
    async handleResize() {
        if (this.pdfDocument && this.currentPage) {
            // 重新渲染当前页面以适应新的窗口大小
            await this.renderPage(this.currentPage);
        }
    },

    // 获取阅读进度
    getReadingProgress() {
        return Utils.storage.get(`reading_${this.bookId}`, null);
    },

    // 智能预加载相邻页面
    async preloadAdjacentPages(currentPage) {
        if (this.isPreloading) return;

        const strategy = this.getPreloadStrategy();
        const pagesToPreload = this.calculatePreloadPages(currentPage, strategy);

        // 添加到预加载队列
        pagesToPreload.forEach(page => this.preloadQueue.add(page));

        // 开始预加载
        this.processPreloadQueue();
    },

    // 获取预加载策略
    getPreloadStrategy() {
        if (this.cacheStrategy === 'aggressive') {
            return { range: 3, priority: 'forward' }; // 预加载前后3页，优先向前
        } else if (this.cacheStrategy === 'conservative') {
            return { range: 1, priority: 'balanced' }; // 只预加载前后1页
        } else {
            // adaptive策略：根据设备性能和网络状况调整
            const isLowEnd = this.isLowEndDevice();
            const connection = navigator.connection;
            const isSlowNetwork = connection && (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g');

            if (isLowEnd || isSlowNetwork) {
                return { range: 1, priority: 'forward' };
            } else {
                return { range: 2, priority: 'balanced' };
            }
        }
    },

    // 计算需要预加载的页面
    calculatePreloadPages(currentPage, strategy) {
        const pages = [];
        const { range, priority } = strategy;

        if (priority === 'forward') {
            // 优先向前预加载
            for (let i = 1; i <= range; i++) {
                const nextPage = currentPage + i;
                if (nextPage <= this.totalPages && !this.pageCache.has(nextPage)) {
                    pages.push(nextPage);
                }
            }
            for (let i = 1; i <= range; i++) {
                const prevPage = currentPage - i;
                if (prevPage >= 1 && !this.pageCache.has(prevPage)) {
                    pages.push(prevPage);
                }
            }
        } else {
            // 平衡预加载
            for (let i = 1; i <= range; i++) {
                const nextPage = currentPage + i;
                const prevPage = currentPage - i;

                if (nextPage <= this.totalPages && !this.pageCache.has(nextPage)) {
                    pages.push(nextPage);
                }
                if (prevPage >= 1 && !this.pageCache.has(prevPage)) {
                    pages.push(prevPage);
                }
            }
        }

        return pages;
    },

    // 处理预加载队列
    async processPreloadQueue() {
        if (this.isPreloading || this.preloadQueue.size === 0) return;

        this.isPreloading = true;
        const startTime = performance.now();

        try {
            // 限制并发预加载数量
            const maxConcurrent = this.isLowEndDevice() ? 1 : 2;
            const pages = Array.from(this.preloadQueue).slice(0, maxConcurrent);

            // 清空已处理的页面
            pages.forEach(page => this.preloadQueue.delete(page));

            // 并发预加载
            await Promise.allSettled(pages.map(page => this.preloadPage(page)));

            const duration = performance.now() - startTime;
            console.log(`预加载完成: ${pages.length}页, 耗时: ${duration.toFixed(2)}ms`);

        } catch (error) {
            console.warn('预加载队列处理失败:', error);
        } finally {
            this.isPreloading = false;

            // 如果队列中还有页面，继续处理
            if (this.preloadQueue.size > 0) {
                setTimeout(() => this.processPreloadQueue(), 100);
            }
        }
    },

    // 优化的预加载单个页面
    async preloadPage(pageNum) {
        if (this.pageCache.has(pageNum) || !this.pdfDocument) return;

        const startTime = performance.now();

        try {
            const page = await this.pdfDocument.getPage(pageNum);
            const viewport = this.calculateViewport(page);

            // 创建优化的离屏画布
            const canvas = this.createOptimizedCanvas(viewport);
            const context = canvas.getContext('2d', {
                alpha: false, // 禁用透明度以提高性能
                desynchronized: true // 允许异步渲染
            });

            // 渲染到离屏画布
            const renderContext = {
                canvasContext: context,
                viewport: viewport,
                intent: 'display',
                enableWebGL: false, // 在预加载时禁用WebGL以节省资源
                renderInteractiveForms: false // 禁用交互表单以提高性能
            };

            await page.render(renderContext).promise;

            // 缓存页面数据
            this.cachePageData(pageNum, {
                canvas: canvas,
                viewport: viewport,
                timestamp: Date.now(),
                renderTime: performance.now() - startTime
            });

            const duration = performance.now() - startTime;
            console.log(`页面 ${pageNum} 预加载完成 (${duration.toFixed(2)}ms)`);

        } catch (error) {
            console.warn(`预加载页面 ${pageNum} 失败:`, error);
            // 从预加载队列中移除失败的页面
            this.preloadQueue.delete(pageNum);
        }
    },

    // 创建优化的画布
    createOptimizedCanvas(viewport) {
        const canvas = document.createElement('canvas');
        const devicePixelRatio = window.devicePixelRatio || 1;

        // 根据设备性能调整像素比例
        const pixelRatio = this.isLowEndDevice() ? Math.min(devicePixelRatio, 1.5) : devicePixelRatio;

        canvas.width = viewport.width * pixelRatio;
        canvas.height = viewport.height * pixelRatio;

        const context = canvas.getContext('2d');
        context.scale(pixelRatio, pixelRatio);

        return canvas;
    },

    // 智能缓存页面数据
    cachePageData(pageNum, data) {
        // 如果缓存已满，使用智能清理策略
        if (this.pageCache.size >= this.maxCacheSize) {
            this.smartCacheCleanup();
        }

        // 添加缓存元数据
        data.accessCount = 1;
        data.lastAccess = Date.now();
        data.priority = this.calculateCachePriority(pageNum);

        this.pageCache.set(pageNum, data);
        console.log(`缓存页面 ${pageNum} (优先级: ${data.priority})`);
    },

    // 智能缓存清理
    smartCacheCleanup() {
        const cacheEntries = Array.from(this.pageCache.entries());

        // 计算每个页面的清理分数（越低越容易被清理）
        const scoredEntries = cacheEntries.map(([page, data]) => {
            const timeSinceAccess = Date.now() - data.lastAccess;
            const distanceFromCurrent = Math.abs(page - this.currentPage);

            // 清理分数 = 距离当前页面的距离 + 时间权重 - 访问次数权重 - 优先级权重
            const score = distanceFromCurrent * 10 +
                         (timeSinceAccess / 60000) * 5 - // 每分钟+5分
                         data.accessCount * 2 -
                         data.priority * 3;

            return { page, data, score };
        });

        // 按分数排序，删除分数最高的页面
        scoredEntries.sort((a, b) => b.score - a.score);

        // 删除25%的缓存页面，但至少删除1页
        const deleteCount = Math.max(1, Math.floor(this.pageCache.size * 0.25));

        for (let i = 0; i < deleteCount && i < scoredEntries.length; i++) {
            const { page } = scoredEntries[i];
            this.pageCache.delete(page);
            console.log(`智能清理缓存页面: ${page} (分数: ${scoredEntries[i].score.toFixed(2)})`);
        }
    },

    // 计算缓存优先级
    calculateCachePriority(pageNum) {
        const distanceFromCurrent = Math.abs(pageNum - this.currentPage);

        if (distanceFromCurrent === 0) return 10; // 当前页面最高优先级
        if (distanceFromCurrent === 1) return 8;  // 相邻页面高优先级
        if (distanceFromCurrent <= 3) return 5;   // 近邻页面中等优先级
        return 2; // 远程页面低优先级
    },

    // 优化的缓存渲染
    renderFromCache(pageNum) {
        const cachedData = this.pageCache.get(pageNum);
        if (!cachedData) return false;

        const startTime = performance.now();

        try {
            const canvas = this.pdfCanvas;
            const context = canvas.getContext('2d');

            // 设置画布尺寸
            canvas.width = cachedData.canvas.width;
            canvas.height = cachedData.canvas.height;
            canvas.style.width = cachedData.viewport.width + 'px';
            canvas.style.height = cachedData.viewport.height + 'px';

            // 使用高性能的图像复制
            context.clearRect(0, 0, canvas.width, canvas.height);

            // 使用 ImageBitmap 进行更快的渲染（如果支持）
            if (window.createImageBitmap && cachedData.imageBitmap) {
                context.drawImage(cachedData.imageBitmap, 0, 0);
            } else {
                context.drawImage(cachedData.canvas, 0, 0);
            }

            // 更新缓存统计
            cachedData.lastAccess = Date.now();
            cachedData.accessCount = (cachedData.accessCount || 0) + 1;

            const renderTime = performance.now() - startTime;
            console.log(`从缓存渲染页面: ${pageNum} (${renderTime.toFixed(2)}ms, 访问次数: ${cachedData.accessCount})`);

            // 记录缓存命中性能
            this.recordCacheHitPerformance(renderTime);

            return true;

        } catch (error) {
            console.error('从缓存渲染失败:', error);
            this.pageCache.delete(pageNum);
            return false;
        }
    },

    // 记录缓存命中性能
    recordCacheHitPerformance(renderTime) {
        if (!this.performanceStats.cacheHitTimes) {
            this.performanceStats.cacheHitTimes = [];
        }

        this.performanceStats.cacheHitTimes.push(renderTime);

        // 只保留最近30次记录
        if (this.performanceStats.cacheHitTimes.length > 30) {
            this.performanceStats.cacheHitTimes.shift();
        }

        // 计算平均缓存命中时间
        const sum = this.performanceStats.cacheHitTimes.reduce((a, b) => a + b, 0);
        this.performanceStats.averageCacheHitTime = sum / this.performanceStats.cacheHitTimes.length;
    },

    // 检查WebGL支持
    checkWebGLSupport() {
        try {
            const canvas = document.createElement('canvas');
            const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
            return !!gl;
        } catch (e) {
            return false;
        }
    },

    // 监控内存使用
    monitorMemoryUsage() {
        if (performance.memory) {
            const memInfo = performance.memory;
            this.performanceStats.memoryUsage = {
                used: memInfo.usedJSHeapSize,
                total: memInfo.totalJSHeapSize,
                limit: memInfo.jsHeapSizeLimit,
                percentage: (memInfo.usedJSHeapSize / memInfo.jsHeapSizeLimit) * 100
            };

            // 如果内存使用超过80%，触发缓存清理
            if (this.performanceStats.memoryUsage.percentage > 80) {
                console.warn('内存使用率过高，触发缓存清理');
                this.aggressiveCacheCleanup();
            }
        }
    },

    // 激进的缓存清理
    aggressiveCacheCleanup() {
        const currentCacheSize = this.pageCache.size;
        const targetSize = Math.max(3, Math.floor(currentCacheSize * 0.5));

        // 保留当前页面和相邻页面
        const protectedPages = new Set([
            this.currentPage,
            this.currentPage - 1,
            this.currentPage + 1
        ]);

        const cacheEntries = Array.from(this.pageCache.entries());
        const deletableEntries = cacheEntries.filter(([page]) => !protectedPages.has(page));

        // 按访问时间排序，删除最旧的
        deletableEntries.sort((a, b) => a[1].lastAccess - b[1].lastAccess);

        const deleteCount = Math.min(deletableEntries.length, currentCacheSize - targetSize);

        for (let i = 0; i < deleteCount; i++) {
            const [page] = deletableEntries[i];
            this.pageCache.delete(page);
            console.log(`激进清理缓存页面: ${page}`);
        }

        // 强制垃圾回收（如果支持）
        if (window.gc) {
            window.gc();
        }
    },

    // 优化的性能统计
    getEnhancedPerformanceStats() {
        this.monitorMemoryUsage();

        const cacheHitRate = this.performanceStats.cacheHitCount + this.performanceStats.cacheMissCount > 0 ?
            (this.performanceStats.cacheHitCount / (this.performanceStats.cacheHitCount + this.performanceStats.cacheMissCount)) * 100 : 0;

        const preloadSuccessRate = this.performanceStats.preloadSuccessCount + this.performanceStats.preloadFailureCount > 0 ?
            (this.performanceStats.preloadSuccessCount / (this.performanceStats.preloadSuccessCount + this.performanceStats.preloadFailureCount)) * 100 : 0;

        return {
            ...this.performanceStats,
            cacheHitRate: cacheHitRate,
            preloadSuccessRate: preloadSuccessRate,
            cacheSize: this.pageCache.size,
            maxCacheSize: this.maxCacheSize,
            preloadQueueSize: this.preloadQueue.size,
            resourceOptimization: this.resourceOptimization
        };
    },

    // 全屏功能
    toggleFullscreen() {
        try {
            if (!document.fullscreenElement) {
                // 进入全屏
                const element = document.documentElement;
                if (element.requestFullscreen) {
                    element.requestFullscreen();
                } else if (element.webkitRequestFullscreen) {
                    element.webkitRequestFullscreen();
                } else if (element.msRequestFullscreen) {
                    element.msRequestFullscreen();
                }

                // 更新按钮图标
                this.updateFullscreenButton(true);

            } else {
                // 退出全屏
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    document.msExitFullscreen();
                }

                // 更新按钮图标
                this.updateFullscreenButton(false);
            }
        } catch (error) {
            console.error('全屏切换失败:', error);
        }
    },

    // 更新全屏按钮
    updateFullscreenButton(isFullscreen) {
        const fullscreenBtn = Utils.dom.$('#fullscreenBtn');
        if (fullscreenBtn) {
            const icon = fullscreenBtn.querySelector('.icon');
            if (icon) {
                icon.textContent = isFullscreen ? '⛶' : '⛶';
            }
            fullscreenBtn.title = isFullscreen ? '退出全屏' : '全屏模式';
        }
    },

    // 监听全屏状态变化
    bindFullscreenEvents() {
        const fullscreenEvents = ['fullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange'];

        fullscreenEvents.forEach(event => {
            Utils.dom.on(document, event, () => {
                const isFullscreen = !!(document.fullscreenElement ||
                                       document.webkitFullscreenElement ||
                                       document.msFullscreenElement);
                this.updateFullscreenButton(isFullscreen);

                // 全屏时重新计算视口
                if (isFullscreen && this.pdfDocument && this.currentPage) {
                    setTimeout(() => {
                        this.renderPage(this.currentPage);
                    }, 100);
                }
            });
        });
    },

    // 页面跳转功能（带翻书效果）
    async goToPage(pageNum) {
        const targetPage = Math.max(1, Math.min(pageNum, this.totalPages));
        if (targetPage !== this.currentPage) {
            const isNext = targetPage > this.currentPage;
            await this.renderPageWithPageTurnEffect(targetPage, isNext);
        }
    },

    // 页面缩放功能
    zoomIn() {
        this.scale = Math.min(this.scale * 1.2, 3.0);
        this.renderPage(this.currentPage);
    },

    zoomOut() {
        this.scale = Math.max(this.scale / 1.2, 0.5);
        this.renderPage(this.currentPage);
    },

    resetZoom() {
        this.scale = 1.0;
        this.renderPage(this.currentPage);
    },

    // 清理资源
    cleanup() {
        // 清理定时器
        if (this.memoryMonitorInterval) {
            clearInterval(this.memoryMonitorInterval);
            this.memoryMonitorInterval = null;
        }

        // 取消当前渲染任务
        if (this.currentRenderTask) {
            this.currentRenderTask.cancel();
            this.currentRenderTask = null;
        }

        // 清理预加载队列
        this.preloadQueue.clear();
        this.isPreloading = false;

        // 清理页面缓存
        this.pageCache.clear();

        // 销毁PDF文档
        if (this.pdfDocument) {
            this.pdfDocument.destroy();
            this.pdfDocument = null;
        }

        // 退出全屏
        if (document.fullscreenElement) {
            try {
                document.exitFullscreen();
            } catch (error) {
                console.warn('退出全屏失败:', error);
            }
        }
    },

    // 翻书效果渲染
    async renderPageWithPageTurnEffect(pageNum, isNext) {
        if (!this.pdfDocument || this.isLoading) return;

        try {
            console.log(`📖 翻书效果: ${this.currentPage} → ${pageNum} (${isNext ? '向前' : '向后'})`);

            // 开始翻书动画
            await this.startPageTurnEffect(isNext);

            // 渲染新页面
            await this.renderPage(pageNum);

            // 完成翻书动画
            await this.completePageTurnEffect();

        } catch (error) {
            console.error('翻书效果渲染失败:', error);
            // 出错时也要完成动画
            await this.completePageTurnEffect();
        }
    },

    // 开始翻书效果
    async startPageTurnEffect(isNext) {
        return new Promise((resolve) => {
            if (this.pdfCanvasContainer) {
                // 添加过渡类
                this.pdfCanvasContainer.classList.add('page-transitioning');

                // 添加翻书方向类
                if (isNext) {
                    this.pdfCanvasContainer.classList.add('page-turn-next');
                } else {
                    this.pdfCanvasContainer.classList.add('page-turn-prev');
                }

                // 等待动画开始
                setTimeout(resolve, 100);
            } else {
                resolve();
            }
        });
    },

    // 完成翻书效果
    async completePageTurnEffect() {
        return new Promise((resolve) => {
            if (this.pdfCanvasContainer) {
                // 移除翻书方向类
                this.pdfCanvasContainer.classList.remove('page-turn-next', 'page-turn-prev');

                // 添加完成类
                this.pdfCanvasContainer.classList.add('page-turn-complete');

                // 等待恢复动画完成
                setTimeout(() => {
                    this.pdfCanvasContainer.classList.remove('page-transitioning', 'page-turn-complete');
                    resolve();
                }, 400);
            } else {
                resolve();
            }
        });
    },

    // 显示开始阅读提示
    showStartReadingHint() {
        // 创建提示元素
        const hint = document.createElement('div');
        hint.className = 'start-reading-hint';
        hint.innerHTML = `
            <div class="hint-content">
                <div class="hint-icon">📖</div>
                <div class="hint-text">请点击屏幕开始阅读</div>
            </div>
        `;

        // 添加样式
        hint.style.cssText = `
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px 30px;
            border-radius: 12px;
            font-size: 16px;
            text-align: center;
            z-index: 10000;
            animation: fadeInOut 3s ease-in-out;
            pointer-events: none;
        `;

        // 添加动画样式
        if (!document.querySelector('#start-reading-hint-style')) {
            const style = document.createElement('style');
            style.id = 'start-reading-hint-style';
            style.textContent = `
                @keyframes fadeInOut {
                    0% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
                    20% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
                    80% { opacity: 1; transform: translate(-50%, -50%) scale(1); }
                    100% { opacity: 0; transform: translate(-50%, -50%) scale(0.8); }
                }
                .hint-content {
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    gap: 10px;
                }
                .hint-icon {
                    font-size: 24px;
                }
                .hint-text {
                    font-weight: 500;
                }
            `;
            document.head.appendChild(style);
        }

        // 添加到页面
        document.body.appendChild(hint);

        // 3秒后自动移除
        setTimeout(() => {
            if (hint.parentElement) {
                hint.remove();
            }
        }, 3000);
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('🚀 DOMContentLoaded 事件触发');

    // 检查必要的依赖
    if (typeof Utils === 'undefined') {
        console.error('❌ Utils工具库未加载');
        alert('错误：工具库未加载，请刷新页面重试');
        return;
    }

    if (typeof pdfjsLib === 'undefined') {
        console.error('❌ PDF.js库未加载');
        alert('错误：PDF.js库未加载，请检查网络连接');
        return;
    }

    console.log('✅ 依赖检查通过，开始初始化阅读器');

    try {
        PDFReaderManager.init();
    } catch (error) {
        console.error('❌ 阅读器初始化异常:', error);
        alert(`阅读器初始化失败: ${error.message}`);
    }
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    PDFReaderManager.cleanup();
});

// 导出到全局
window.PDFReaderManager = PDFReaderManager;
